import React, {useEffect, useState} from 'react';
import {useLocation} from 'umi';
import {ProCard, ProColumns, ProDescriptions, ProDescriptionsItemProps} from "@ant-design/pro-components";
import {Button, Col, Descriptions, Drawer, message, Row, Space, Statistic} from "antd";
import {RedoOutlined} from "@ant-design/icons";
import {stageStat} from '@/services/stage-stat-api'
import {restart, doSwitch} from '@/services/switch-warmup-api'
import {findOne} from '@/services/node-api';
import {remove} from '@/services/position-api';
import {enumInKeyDefault} from "@/utils/calculateUtil";
import {MainStemStatus} from "@/services/ant-design-pro/enums";
import {descriptionColumns} from "@/pages/Node";
import moment from "moment";

export type StageStatProps = {
  pipelineId?: number;
  key?: number;
}




const positionColumns :ProColumns<API.PositionEventData>[] = [
  {
    title: '位点信息',
    dataIndex: ['position']
  },
];

const StageStat: React.FC<StageStatProps> = (props) => {

  const [stat, setStat] = useState<API.StageStatDTO>();
  const location = useLocation();
  // @ts-ignore
  const pipelineId = props?.pipelineId || location?.state?.pipelineId || null;
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [position, handlePosition] = useState<API.PositionEventData>();
  const [nid, handleNid] = useState<string>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      const res = await remove(pipelineId);
      hide();
      if (res) {
        message.success('删除成功');
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };

  const refresh = async () => {
    const hide = message.loading('加载中....');
    try {
      const stat = await stageStat({pipelineId: pipelineId})
      hide();
      if (stat) {
        setStat(stat);
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  }

  const switchWarm = async () => {
    const hide = message.loading('切换中....');
    try {
      const res = await doSwitch(pipelineId);
      hide();
      if (res) {
        await refresh();
      }
      return true;
    } catch (error) {
      hide();
      return false;
    }

  }

  const doRestart = async () => {
    const hide = message.loading('重启中....');
    try {
      const res = await restart(pipelineId);
      hide();
      if (res) {
        await refresh();
      }
      return true;
    } catch (error) {
      hide();
      return false;
    }
  }

  useEffect(() => {
    stageStat({pipelineId: pipelineId}).then(d => setStat(d));
  }, [props?.key]);

  return (
    <ProCard direction="column" ghost gutter={[0, 16]}>
      <ProCard>
        <Row>
          <Col md={3} sm={3} xs={3}>
            <Statistic title="SELECT" value={0}/>
          </Col>
          <Col md={3} sm={3} xs={3}>
            <Statistic title="EXTRACT" value={0}/>
          </Col>
          <Col md={3} sm={3} xs={3}>
            <Statistic title="TRANSFORM" value={0}/>
          </Col>
          <Col md={3} sm={3} xs={3}>
            <Statistic title="LOAD" value={0}/>
          </Col>
          <Col md={3} sm={3} xs={3}>
            <Statistic title="RUNNING" value={0}/>
          </Col>
          <Col md={3} sm={3} xs={3}>
            <Statistic title="END" value={0}/>
          </Col>
          <Col md={3} sm={3} xs={3}>
            <Button type={'primary'} onClick={refresh}><RedoOutlined/></Button>
          </Col>
        </Row>
      </ProCard>
      <ProCard gutter={8}>
        <ProCard layout="center" bordered title="mainstem"  style={{maxWidth: 300}}>
          <Descriptions extra={<Space>
            {stat?.mainstemData?.status === 'TAKEING' && <>
              <Button type={'link'} onClick={switchWarm}>切换</Button>
              <Button type={'link'} onClick={doRestart}>重启</Button>
            </>}
            {stat?.mainstemData?.status === 'OVERTAKE' && <>
              <Button type={'link'} onClick={() => {setShowDetail(true)}}>查看</Button>
              <Button type={'link'} onClick={switchWarm}>切换</Button>
              <Button type={'link'} onClick={doRestart}>重启</Button>
            </>}
          </Space>}>
            {stat?.mainstemData?.status === 'OVERTAKE' && <Descriptions.Item label={"nid"}>{stat?.mainstemData?.nid}</Descriptions.Item>}
            <Descriptions.Item label="mainstem状态"> {enumInKeyDefault(MainStemStatus, stat?.mainstemData?.status,'未工作')}</Descriptions.Item>
          </Descriptions>
        </ProCard>
        <ProCard layout="center" bordered title="position" style={{maxWidth: 300}}>
          {stat?.positionData ?
            <>
            <Descriptions extra={<>
              <Space>
                <Button type={'link'} onClick={() => handlePosition(stat?.positionData)}>查看</Button>
                {stat?.channelStatus === 'STOP' &&  <Button type={'link'} onClick={handleRemove}>删除</Button>}
              </Space>
            </>}>
              <Descriptions.Item label="最后更新时间">{moment(stat?.positionData?.modifiedTime).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            </Descriptions>
            </>
            : <>无信息</>
          }
        </ProCard>
      </ProCard>
      <Drawer
        width={500}
        open={showDetail}
        onClose={() => {
          setShowDetail(false);
          handleNid(undefined);
          handlePosition(undefined);
        }}
        closable={false}
      >
        {nid && (
          <ProDescriptions<API.Node>
            column={2}
            request={async () => findOne(stat?.mainstemData?.nid)}
            columns={descriptionColumns as ProDescriptionsItemProps<API.Node>[]}
          />
        )}
        {position && (
          <ProDescriptions<API.PositionEventData>
            column={2}
            dataSource={position}
            columns={positionColumns as ProDescriptionsItemProps<API.PositionEventData>[]}
          />
        )}
      </Drawer>
    </ProCard>
  );
};

export default StageStat;
